package com.czy;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;

public class 工作时间和休息时间计算出工时 {

    public static void main(String[] args) {
        LocalTime workStartTime = LocalTime.of(22, 0);
        LocalTime workEndTime = LocalTime.of(8, 0);
        LocalTime restStartTime = LocalTime.of(23, 0);
        LocalTime restEndTime = LocalTime.of(1, 0);

        if(restStartTime == null || restEndTime == null) {
            System.out.println(ChronoUnit.MINUTES.between(LocalDateTime.of(LocalDate.now(), workStartTime),LocalDateTime.of(LocalDate.now().plusDays(workEndTime.isBefore(workStartTime) ? 1 : 0), workEndTime)));
            System.exit(0);
        }

        List<int[]> workPeriods = splitIntoMinutes(workStartTime, workEndTime);
        List<int[]> restPeriods = splitIntoMinutes(restStartTime, restEndTime);

        int totalWorkMinutes = calculateTotalMinutes(workPeriods);
        int totalRestOverlap = calculateOverlap(workPeriods, restPeriods);

        int resultMinutes = totalWorkMinutes - totalRestOverlap;

        System.out.println("实际工作时间（分钟）: " + resultMinutes);
    }

    private static List<int[]> splitIntoMinutes(LocalTime start, LocalTime end) {
        List<int[]> result = new ArrayList<>();
        int startMin = start.getHour() * 60 + start.getMinute();
        int endMin = end.getHour() * 60 + end.getMinute();

        if (endMin <= startMin) {
            // 跨天，拆分为两部分
            result.add(new int[]{startMin, 1440});
            result.add(new int[]{0, endMin});
        } else {
            result.add(new int[]{startMin, endMin});
        }
        return result;
    }

    private static int calculateTotalMinutes(List<int[]> periods) {
        int total = 0;
        for (int[] period : periods) {
            total += period[1] - period[0];
        }
        return total;
    }

    private static int calculateOverlap(List<int[]> workPeriods, List<int[]> restPeriods) {
        int total = 0;
        for (int[] work : workPeriods) {
            for (int[] rest : restPeriods) {
                int overlapStart = Math.max(work[0], rest[0]);
                int overlapEnd = Math.min(work[1], rest[1]);
                if (overlapStart < overlapEnd) {
                    total += (overlapEnd - overlapStart);
                }
            }
        }
        return total;
    }
}